const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const vscode = require('vscode');
const { refreshDevLogin, getCurrentAccount } = require('./refreshLogin');
const GlobalConfig = require('./view/globalConfig');
const fs = require('fs');
const path = require('path');

// 获取项目文件路径
function getProjectFile(relativePath, workspacePath = null) {
    try {
        // 如果指定了工作区路径，使用指定的路径
        if (workspacePath) {
            return path.join(workspacePath, relativePath);
        }
        
        // 否则使用第一个工作区路径（向后兼容）
        if (!vscode.workspace.workspaceFolders || !vscode.workspace.workspaceFolders.length) {
            return null
        }
        const defaultWorkspacePath = vscode.workspace.workspaceFolders[0].uri.fsPath;
        return path.join(defaultWorkspacePath, relativePath);
    } catch (error) {
        return null;
    }
}

// 从.env文件读取端口配置
function getPortFromEnv(portKey, defaultPort, workspacePath = null) {
    const envPath = getProjectFile('.env', workspacePath)
    if (!envPath || !fs.existsSync(envPath)) return defaultPort

    const envData = fs.readFileSync(envPath, 'utf8');
    const portLine = envData.split('\n').find(line => line.startsWith(`${portKey}=`))
    if (!portLine) return defaultPort

    const port = parseInt(portLine.split('=')[1])
    return isNaN(port) ? defaultPort : port
}

// 保存端口配置到.env文件
function savePortToEnv(portKey, port, workspacePath = null) {
    const envPath = getProjectFile('.env', workspacePath)
    if (!envPath) return;
    
    let envData = '';
    if (fs.existsSync(envPath)) {
        envData = fs.readFileSync(envPath, 'utf8');
    }

    const lines = envData.split('\n');
    const portIndex = lines.findIndex(line => line.startsWith(`${portKey}=`));
    
    if (portIndex !== -1) {
        // 更新现有的端口
        lines[portIndex] = `${portKey}=${port}`;
    } else {
        // 添加新的端口配置
        lines.push(`${portKey}=${port}`);
    }

    // 确保文件以换行符结尾
    const newContent = lines.join('\n');
    fs.writeFileSync(envPath, newContent.endsWith('\n') ? newContent : newContent + '\n', 'utf8');
    
    console.log(`端口配置已保存到.env文件: ${portKey}=${port}`);
}

class HttpServerManager {
    constructor(workspacePath = null) {
        this.app = new Koa();
        this.router = new Router();
        this.server = null;
        this.workspacePath = workspacePath;
        
        // 从.env文件读取端口配置，如果没有则使用默认端口3737
        this.port = getPortFromEnv('HTTP_SERVER_PORT', 3737, this.workspacePath);
        console.log(`HTTP服务器端口设置为: ${this.port} (工作区: ${this.workspacePath || 'default'})`);
        
        this.setupMiddleware();
        this.setupRoutes();
    }

    setupMiddleware() {
        // JSON解析中间件
        this.app.use(bodyParser());

        // 错误处理中间件
        this.app.use(async (ctx, next) => {
            try {
                await next();
            } catch (error) {
                console.error('Koa错误:', error);
                ctx.status = 500;
                ctx.body = { 
                    error: '服务器内部错误', 
                    message: error.message 
                };
            }
        });
    }

    setupRoutes() {
        // 健康检查接口
        this.router.get('/api/health', async (ctx) => {
            ctx.body = {
                status: 'ok',
                message: 'Web Login Plugin API服务运行正常',
                port: this.port,
                timestamp: new Date().toISOString()
            };
        });

        // 刷新登录接口
        this.router.post('/api/refreshLogin', async (ctx) => {
            const body = ctx.request.body;
            const domain = body && body.domain;
            const loginId = body && body.loginId;
            const url = body && body.url;

            // 验证必需的字段
            if (!domain || !loginId || !url) {
                ctx.status = 400;
                ctx.body = {
                    error: '缺少必需参数',
                    required: ['domain', 'loginId', 'url']
                };
                return;
            }

            // 从本地配置中查找账号
            const accountConfig = await this.findAccountConfig(domain, loginId, url);

            if (!accountConfig) {
                ctx.status = 404;
                ctx.body = {
                    error: '未找到匹配的账号配置',
                    message: `未找到 domain="${domain}", loginId="${loginId}" 和 url="${url}" 的账号配置`
                };
                return;
            }

            // 检查必需的登录信息
            if (!accountConfig.password) {
                ctx.status = 400;
                ctx.body = {
                    error: '账号配置不完整',
                    message: '找到的账号配置缺少密码信息'
                };
                return;
            }

            // 设置默认值
            const config = {
                ...accountConfig,
            };

            try {
                // API模式调用登录，只返回token不打开浏览器
                const loginResult = await refreshDevLogin(config, true);

                ctx.body = {
                    success: true,
                    message: loginResult.message,
                    token: loginResult.token,
                    loginTime: loginResult.loginTime,
                    config: {
                        env: config.env,
                        domain: config.domain,
                        loginId: config.loginId,
                        host: config.host,
                        port: config.port
                    }
                };
            } catch (error) {
                console.error('API登录失败:', error);
                ctx.status = 500;
                ctx.body = {
                    success: false,
                    error: '登录失败',
                    message: error.message
                };
                return;
            }
        });

        // 获取当前账号接口
        this.router.get('/api/getCurrentAccount', async (ctx) => {
            const currentAccount = getCurrentAccount();
            ctx.body = {
                success: true,
                data: currentAccount
            };
        });

        // 获取所有账号列表接口
        this.router.get('/api/getAllAccounts', async (ctx) => {
            try {
                const accountsStr = await GlobalConfig.readConfig('webLoginPlugin.accounts') || '[]';
                const accounts = JSON.parse(accountsStr);

                // 格式化账号信息，移除敏感信息如密码
                const formattedAccounts = accounts.map(envGroup => ({
                    env: envGroup.env,
                    label: envGroup.label,
                    children: envGroup.children ? envGroup.children.map(account => ({
                        label: account.label,
                        domain: account.domain,
                        loginId: account.loginId,
                        url: account.url,
                        host: account.host,
                        port: account.port,
                        browser: account.browser
                        // 注意：不返回密码等敏感信息
                    })) : []
                }));

                ctx.body = {
                    success: true,
                    data: formattedAccounts,
                    total: formattedAccounts.reduce((sum, env) => sum + (env.children ? env.children.length : 0), 0)
                };
            } catch (error) {
                console.error('获取账号列表失败:', error);
                ctx.status = 500;
                ctx.body = {
                    success: false,
                    error: '获取账号列表失败',
                    message: error.message
                };
            }
        });

        // 注册路由
        this.app.use(this.router.routes());
        this.app.use(this.router.allowedMethods());

        // 404处理
        this.app.use(async (ctx) => {
            if (ctx.respond !== false) {
                ctx.status = 404;
                ctx.body = { error: '接口不存在' };
            }
        });
    }

    async findAccountConfig(domain, loginId, url) {
        try {
            const accountsStr = await GlobalConfig.readConfig('webLoginPlugin.accounts') || '[]';
            const accounts = JSON.parse(accountsStr);

            // 在所有环境中查找匹配的账号
            for (const envGroup of accounts) {
                if (envGroup.children) {
                    for (const account of envGroup.children) {
                        if (account.domain === domain &&
                            account.loginId === loginId &&
                            account.url === url) {
                            // 返回完整的账号配置，包含环境信息
                            return {
                                ...account,
                                env: envGroup.env
                            };
                        }
                    }
                }
            }

            return null;
        } catch (error) {
            console.error('查找账号配置失败:', error);
            return null;
        }
    }

    start() {
        return new Promise((resolve, reject) => {
            // 如果服务器已经在运行，先停止
            if (this.server) {
                this.stop();
            }

            const tryListen = (port) => {
                this.server = this.app.listen(port, 'localhost', () => {
                    this.port = port;
                    console.log(`Web Login Plugin HTTP服务已启动，端口: ${this.port} (工作区: ${this.workspacePath || 'default'})`);
                    
                    // 保存实际使用的端口到.env文件
                    savePortToEnv('HTTP_SERVER_PORT', this.port, this.workspacePath);
                    
                    resolve(this.port);
                });

                this.server.on('error', (err) => {
                    if (err.code === 'EADDRINUSE') {
                        // 端口被占用，尝试下一个端口
                        tryListen(port + 1);
                    } else {
                        reject(err);
                    }
                });
            };

            tryListen(this.port);
        });
    }

    stop() {
        if (this.server) {
            this.server.close();
            this.server = null;
            console.log('Web Login Plugin HTTP服务已停止');
        }
    }

    getPort() {
        return this.port;
    }
}

module.exports = HttpServerManager; 